package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.FixedAssetCancellation;
import com.amsp.oa.oademo.mapper.FixedAssetCancellationMapper;
import com.amsp.oa.oademo.service.FixedAssetCancellationService;
import com.amsp.oa.oademo.vo.FixedAssetCancellationVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class FixedAssetCancellationServiceImpl extends ServiceImpl<FixedAssetCancellationMapper, FixedAssetCancellation>
        implements FixedAssetCancellationService {

    @Override
    public IPage<FixedAssetCancellation> getList(Integer page, Integer size, String month, String department) {
        LambdaQueryWrapper<FixedAssetCancellation> queryWrapper = new LambdaQueryWrapper<>();

        // 如果指定了月份，则按月份筛选
        if (StringUtils.hasText(month)) {
            String[] parts = month.split("-");
            if (parts.length == 2) {
                int year = Integer.parseInt(parts[0]);
                int monthValue = Integer.parseInt(parts[1]);

                LocalDate startDate = LocalDate.of(year, monthValue, 1);
                LocalDate endDate = startDate.plusMonths(1).minusDays(1);

                queryWrapper.between(FixedAssetCancellation::getApplicationDate, startDate, endDate);
            }
        }

        // 如果指定了部门，则按部门筛选
        if (StringUtils.hasText(department)) {
            queryWrapper.like(FixedAssetCancellation::getCustodyDepartment, department);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(FixedAssetCancellation::getCreateTime);

        return page(new Page<>(page, size), queryWrapper);
    }

    @Override
    public FixedAssetCancellationVO getDetail(Long id) {
        FixedAssetCancellation entity = getById(id);
        if (entity == null) {
            return null;
        }

        return convertToVO(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(FixedAssetCancellationVO vo) {
        FixedAssetCancellation entity = convertToEntity(vo);
        return saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(List<Long> ids) {
        return removeByIds(ids);
    }

    /**
     * 将实体转换为VO
     */
    private FixedAssetCancellationVO convertToVO(FixedAssetCancellation entity) {
        if (entity == null) {
            return null;
        }

        FixedAssetCancellationVO vo = new FixedAssetCancellationVO();
        vo.setId(entity.getId());
        vo.setNo(entity.getRequestNo());
        vo.setIsEquipment(entity.getIsEquipment());
        vo.setIsInstrument(entity.getIsInstrument());
        vo.setIsFixture(entity.getIsFixture());
        vo.setIsTool(entity.getIsTool());
        vo.setIsOther(entity.getIsOther());
        vo.setCustodyDepartment(entity.getCustodyDepartment());

        // 处理申请日期
        if (entity.getApplicationDate() != null) {
            vo.setApplicationDateYear(String.valueOf(entity.getApplicationDate().getYear()));
            vo.setApplicationDateMonth(String.valueOf(entity.getApplicationDate().getMonthValue()));
            vo.setApplicationDateDay(String.valueOf(entity.getApplicationDate().getDayOfMonth()));
        }

        vo.setIsScrapped(entity.getIsScrapped());
        vo.setIsLost(entity.getIsLost());
        vo.setIsSoldAtDiscount(entity.getIsSoldAtDiscount());
        vo.setAssetNumber(entity.getAssetNumber());
        vo.setAssetName(entity.getAssetName());
        vo.setModel(entity.getModel());
        vo.setSpecification(entity.getSpecification());

        // 处理购入日期
        if (entity.getPurchaseDate() != null) {
            vo.setPurchaseDate(entity.getPurchaseDate().format(DateTimeFormatter.ISO_DATE));
        }

        vo.setPurchaseAmount(entity.getPurchaseAmount());
        vo.setDepreciatedAmount(entity.getDepreciatedAmount());
        vo.setResidualValue(entity.getResidualValue());
        vo.setEstimatedProfitLoss(entity.getEstimatedProfitLoss());
        vo.setApplicationReason(entity.getApplicationReason());
        vo.setSuggestedDisposalPlan(entity.getSuggestedDisposalPlan());
        vo.setGeneralManager(entity.getGeneralManager());
        vo.setDirector(entity.getDirector());
        vo.setDepartmentManager(entity.getDepartmentManager());
        vo.setSupervisor(entity.getSupervisor());
        vo.setCustodian(entity.getCustodian());
        vo.setPresidentOpinion(entity.getPresidentOpinion());
        vo.setSpecializedDepartmentOpinion(entity.getSpecializedDepartmentOpinion());
        vo.setFinanceDepartmentOpinion(entity.getFinanceDepartmentOpinion());
        vo.setUndertaker1(entity.getUndertaker1());
        vo.setUndertaker2(entity.getUndertaker2());

        // 处理核准申请日期
        if (entity.getApprovalDate() != null) {
            vo.setApprovalDateYear(String.valueOf(entity.getApprovalDate().getYear()));
            vo.setApprovalDateMonth(String.valueOf(entity.getApprovalDate().getMonthValue()));
            vo.setApprovalDateDay(String.valueOf(entity.getApprovalDate().getDayOfMonth()));
        }

        vo.setDisposalResultReport(entity.getDisposalResultReport());
        vo.setIsSalesProof(entity.getIsSalesProof());
        vo.setIsPaymentReceipt(entity.getIsPaymentReceipt());
        vo.setIsMachineResume(entity.getIsMachineResume());
        vo.setGeneralManager2(entity.getGeneralManager2());
        vo.setDirector2(entity.getDirector2());
        vo.setDepartmentManager2(entity.getDepartmentManager2());
        vo.setSupervisor2(entity.getSupervisor2());
        vo.setPresidentOpinion2(entity.getPresidentOpinion2());
        vo.setFinanceManagementOpinion(entity.getFinanceManagementOpinion());
        vo.setIsApproved(entity.getIsApproved());
        vo.setEnterpriseManagementOpinion(entity.getEnterpriseManagementOpinion());
        vo.setUndertaker3(entity.getUndertaker3());

        return vo;
    }

    /**
     * 将VO转换为实体
     */
    private FixedAssetCancellation convertToEntity(FixedAssetCancellationVO vo) {
        if (vo == null) {
            return null;
        }

        FixedAssetCancellation entity = new FixedAssetCancellation();
        entity.setId(vo.getId());
        entity.setRequestNo(vo.getNo());
        entity.setIsEquipment(vo.getIsEquipment());
        entity.setIsInstrument(vo.getIsInstrument());
        entity.setIsFixture(vo.getIsFixture());
        entity.setIsTool(vo.getIsTool());
        entity.setIsOther(vo.getIsOther());
        entity.setCustodyDepartment(vo.getCustodyDepartment());

        // 处理申请日期
        if (StringUtils.hasText(vo.getApplicationDateYear()) &&
                StringUtils.hasText(vo.getApplicationDateMonth()) &&
                StringUtils.hasText(vo.getApplicationDateDay())) {
            try {
                int year = Integer.parseInt(vo.getApplicationDateYear());
                int month = Integer.parseInt(vo.getApplicationDateMonth());
                int day = Integer.parseInt(vo.getApplicationDateDay());
                entity.setApplicationDate(LocalDate.of(year, month, day));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        entity.setIsScrapped(vo.getIsScrapped());
        entity.setIsLost(vo.getIsLost());
        entity.setIsSoldAtDiscount(vo.getIsSoldAtDiscount());
        entity.setAssetNumber(vo.getAssetNumber());
        entity.setAssetName(vo.getAssetName());
        entity.setModel(vo.getModel());
        entity.setSpecification(vo.getSpecification());

        // 处理购入日期
        if (StringUtils.hasText(vo.getPurchaseDate())) {
            try {
                entity.setPurchaseDate(LocalDate.parse(vo.getPurchaseDate()));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        entity.setPurchaseAmount(vo.getPurchaseAmount());
        entity.setDepreciatedAmount(vo.getDepreciatedAmount());
        entity.setResidualValue(vo.getResidualValue());
        entity.setEstimatedProfitLoss(vo.getEstimatedProfitLoss());
        entity.setApplicationReason(vo.getApplicationReason());
        entity.setSuggestedDisposalPlan(vo.getSuggestedDisposalPlan());
        entity.setGeneralManager(vo.getGeneralManager());
        entity.setDirector(vo.getDirector());
        entity.setDepartmentManager(vo.getDepartmentManager());
        entity.setSupervisor(vo.getSupervisor());
        entity.setCustodian(vo.getCustodian());
        entity.setPresidentOpinion(vo.getPresidentOpinion());
        entity.setSpecializedDepartmentOpinion(vo.getSpecializedDepartmentOpinion());
        entity.setFinanceDepartmentOpinion(vo.getFinanceDepartmentOpinion());
        entity.setUndertaker1(vo.getUndertaker1());
        entity.setUndertaker2(vo.getUndertaker2());

        // 处理核准申请日期
        if (StringUtils.hasText(vo.getApprovalDateYear()) &&
                StringUtils.hasText(vo.getApprovalDateMonth()) &&
                StringUtils.hasText(vo.getApprovalDateDay())) {
            try {
                int year = Integer.parseInt(vo.getApprovalDateYear());
                int month = Integer.parseInt(vo.getApprovalDateMonth());
                int day = Integer.parseInt(vo.getApprovalDateDay());
                entity.setApprovalDate(LocalDate.of(year, month, day));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        entity.setDisposalResultReport(vo.getDisposalResultReport());
        entity.setIsSalesProof(vo.getIsSalesProof());
        entity.setIsPaymentReceipt(vo.getIsPaymentReceipt());
        entity.setIsMachineResume(vo.getIsMachineResume());
        entity.setGeneralManager2(vo.getGeneralManager2());
        entity.setDirector2(vo.getDirector2());
        entity.setDepartmentManager2(vo.getDepartmentManager2());
        entity.setSupervisor2(vo.getSupervisor2());
        entity.setPresidentOpinion2(vo.getPresidentOpinion2());
        entity.setFinanceManagementOpinion(vo.getFinanceManagementOpinion());
        entity.setIsApproved(vo.getIsApproved());
        entity.setEnterpriseManagementOpinion(vo.getEnterpriseManagementOpinion());
        entity.setUndertaker3(vo.getUndertaker3());

        return entity;
    }
}